package com.tanhua.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.domain.db.Announcement;
import com.tanhua.domain.web.PageBean;
import com.tanhua.domain.web.ResultInfo;
import com.tanhua.dubbo.api.MessagesApi;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class AnnouncementService {

    @Reference
    private MessagesApi messagesApi;

    //分页查找所有公告
    public ResponseEntity<Object> findAll(Integer page,Integer pagesize) {
        IPage<Announcement> iPage = messagesApi.findAnnouncements(page, pagesize);

        List<Announcement> records = iPage.getRecords();

        return ResponseEntity.ok(new PageBean<>(records,(int)iPage.getTotal(),page,pagesize));
    }

    //修改公告
    public ResultInfo update(Map<String, String> param) {
        log.info("================调用update=================");
        String title = param.get("title");
        String description = param.get("description");
        String id = param.get("id");

        Announcement announcement = new Announcement();
        announcement.setId(Long.parseLong(id));
        announcement.setTitle(title);
        announcement.setDescription(description);
        announcement.setUpdated(new Date());

        messagesApi.updateById(announcement);

        return new ResultInfo(true,"修改成功");
    }

    //添加公告
    public ResultInfo save(Map<String, String> param) {
        log.info("================调用save=================");
        String title = param.get("title");
        String description = param.get("description");

        Announcement announcement = new Announcement();
        announcement.setTitle(title);
        announcement.setDescription(description);
        announcement.setUpdated(new Date());
        announcement.setCreated(new Date());


        messagesApi.save(announcement);

        return new ResultInfo(true,"添加成功");
    }

    //删除公告
    public ResultInfo delete(Long id) {
        messagesApi.delete(id);
        return new ResultInfo(true,"删除成功");
    }
}
